<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\func\Lib;
use app\common\func\Libs;
use app\common\func\Tools;
use app\common\model\Policy;
use app\common\model\PolicyRelation;
use app\common\model\Product;
use app\common\model\ProductApply;
use app\common\model\User;
use think\Db;

class Datas extends Api
{
    protected $noNeedLogin = ['transactionStatistics', 'getProductDayIncome'];
    protected $noNeedRight = '*';

    /**
     * 获取团队所有代理ID
     */
    public function getAllTeam()
    {
        $userId = 1;
        $data = Lib::getTeamAllUser($userId);
        // dump($data);
    }

    /**
     * 数据 获取我的团队
     */
    public function getMyDirectlyTeam()
    {
        $type = $this->request->post('type', 1);
        $productId = $this->request->post('product_id', 3);
        $allTitle = '全部';
        $team = [
            ["id" => 'all', "name" => $allTitle, "type" => 'ALL', "selected" => 'active'],
            ["id" => 0, "name" => '我的直营', "type" => 'MY', "selected" => '']
        ];
        $data = Lib::getProductTeams5($this->auth->id, $productId);
        $team = array_merge_recursive($team, $data->items());
        $this->success('获取成功', $team);
    }

    /**
     * 数据 获取统计信息
     */
    public function getTotalData_bak()
    {
        $now = time();
        $month = strtotime(date("Y-m", $now));
        $data = [
            "tran" => [
                'self_total' => '0.00',
                'self_num' => 0,
                'team_total' => '0.00',
                'team_num' => 0,
                'all_total' => '0.00'
            ],
            "active" => [
                'self_total' => 0,
                'team_total' => 0,
                'all_total'
            ],
            "team" => [
                'month' => 0,
                'total' => 0
            ]
        ];

        $product = Lib::getMyProduct5($this->auth->id, 2);
        $teamIds = Lib::getTeamAllUser($this->auth->id, 2);
        foreach ($product as $val) {
            if (!empty($val["table_name"])) {
                $self_tran_data = Lib::getTeamTranData([$this->auth->id], $val["table_name"], $val["id"], 1);
                $team_tran_data = Lib::getTeamTranData($teamIds, $val["table_name"], $val["id"], 1);
                $data["tran"]["self_num"] += $self_tran_data["total"];
                $data["tran"]["self_total"] = bcadd($data["tran"]["self_total"], $self_tran_data["sum"], 2);
                $data["tran"]["team_num"] += $team_tran_data["total"];
                $data["tran"]["team_total"] = bcadd($data["tran"]["team_total"], $team_tran_data["sum"], 2);
                $self_active_data = Lib::getTeamActiveData([$this->auth->id], $val['id'], 1);
                $team_active_data = Lib::getTeamActiveData($teamIds, $val['id'], 1);
                $data["active"]["self_total"] += $self_active_data["total"];
                $data["active"]["team_total"] += $team_active_data["total"];
            }
        }
        $myTeam = User::where(['pid' => $this->auth->id, 'ptype' => 2, 'status' => 'normal', 'is_virtual' => 1])->field("count(id) as total")->find();
        $data["team"]["month"] = $myTeam["total"];
        $data["team"]["total"] = count($teamIds);
        $data["tran"]["all_total"] = bcadd($data["tran"]["self_total"], $data["tran"]["team_total"], 2);
        $data["active"]["all_total"] = $data["active"]["self_total"] + $data["active"]["team_total"];




        $bonus = \app\api\controller\bonus\Datas::instance()->get_total($this->auth->id);
        $data = array_merge($data, $bonus);

        $this->success('获取成功', $data);
    }

    /**
     * 数据 获取统计信息
     */
    public function getTotalData()
    {
        $now = time();
        $month = strtotime(date("Y-m", $now));
        $data = [
            "tran" => [
                'self_total' => '0.00',
                'team_total' => '0.00',
                'all_total' => '0.00'
            ],
            "active" => [
                'self_total' => 0,
                'team_total' => 0,
                'all_total'
            ],
            "team" => [
                'month' => 0,
                'total' => 0
            ]
        ];

        $product = Lib::getMyProduct5($this->auth->id, 2);
        $teamIds = Lib::getTeamAllUser5($this->auth->id, 2);
        $productIds = [];
        foreach ($product as $val) {
            $productIds[] = $val["id"];
            if (!empty($val["table_name"])) {
                $self_active_data = Lib::getTeamActiveData([$this->auth->id], $val['id'], 1);
                $team_active_data = Lib::getTeamActiveData($teamIds, $val['id'], 1);
                $data["active"]["self_total"] += $self_active_data["total"];
                $data["active"]["team_total"] += $team_active_data["total"];
            }
        }
        $myTeam = User::where(['pid' => $this->auth->id, 'ptype' => 2, 'status' => 'normal', 'is_virtual' => 1])->field("count(id) as total")->find();
        $data["team"]["month"] = $myTeam["total"];
        $data["team"]["total"] = count($teamIds);

        // 交易

        $self_tran_data = Lib::getTeamTranDataNew([$this->auth->id], $productIds, 1);
        $team_tran_data = Lib::getTeamTranDataNew($teamIds, $productIds, 1);
        $data["tran"]["self_total"] = bcadd($data["tran"]["self_total"], $self_tran_data["sum"], 2);
        $data["tran"]["team_total"] = bcadd($data["tran"]["team_total"], $team_tran_data["sum"], 2);

        $data["tran"]["all_total"] = bcadd($data["tran"]["self_total"], $data["tran"]["team_total"], 2);
        $data["active"]["all_total"] = $data["active"]["self_total"] + $data["active"]["team_total"];

        $bonus = \app\api\controller\bonus\Datas::instance()->get_total($this->auth->id);
        $data = array_merge($data, $bonus);

        $this->success('获取成功', $data);
    }


    /**
     * 数据 按分类统计 - 交易
     */
    public function getProductTranTotalData()
    {
        $type = $this->request->post('type', 1);
        $product = Lib::getMyProduct5($this->auth->id, 2);
        $ids = [$this->auth->id];
        if ($type == 2) {
            $ids = Lib::getTeamAllUser($this->auth->id, 2);
        }
        $dayStartTime = strtotime('-1 day', strtotime(date('Y-m-d')));
        $dayEndTime = strtotime(date('Y-m-d'));
        $monthStartTime = strtotime(date('Y-m'));
        $monthEndTime = time();
        foreach ($product as $key => $val) {
            $product[$key]["day_date"] = date('m-d', $dayStartTime);
            $product[$key]["day_total"] = '0.00';
            $product[$key]["month_total"] = '0.00';
            $product[$key]["day_hb_type"] = 2;
            $product[$key]["day_hb"] = 0;
            $product[$key]["month_hb_type"] = 2;
            $product[$key]["month_hb"] = 0;
            if (!empty($val["table_name"])) {
                $dayData = Lib::getTeamTranData($ids, $val["table_name"], $val["id"], 2, $dayStartTime, $dayEndTime);
                $prevDayData = Lib::getTeamTranData($ids, $val["table_name"], $val["id"], 2, strtotime('-1 month', $dayStartTime), strtotime('-1 month', $dayEndTime));
                $monthData = Lib::getTeamTranData($ids, $val["table_name"], $val["id"], 2, $monthStartTime, $monthEndTime);
                $prevMonthData = Lib::getTeamTranData($ids, $val["table_name"], $val["id"], 2, strtotime('-1 month', $monthStartTime), strtotime('-1 month', $monthEndTime));
                $product[$key]["day_total"] = $dayData["sum"];
                $product[$key]["month_total"] = $monthData["sum"];
                $hbDayData = calculateHb($dayData['sum'], $prevDayData["sum"]);
                $product[$key]["day_hb_type"] = $hbDayData["hb_type"];
                $product[$key]["day_hb"] = $hbDayData["hb_num"];
                $hbMonthData = calculateHb($monthData['sum'], $prevMonthData["sum"]);
                $product[$key]["month_hb_type"] = $hbMonthData["hb_type"];
                $product[$key]["month_hb"] = $hbMonthData["hb_num"];
            }
        }
        $this->success('获取成功', $product);
    }

    /**
     * 数据 按分类统计 - 激活
     */
    public function getProductActiveTotalData()
    {
        $type = $this->request->post('type', 1);
        $product = Lib::getMyProduct5($this->auth->id, 2);
        $ids = [$this->auth->id];
        if ($type == 2) {
            $ids = Lib::getTeamAllUser($this->auth->id, 2);
        }
        $dayStartTime = strtotime('-1 day', strtotime(date('Y-m-d')));
        $dayEndTime = strtotime(date('Y-m-d'));
        $monthStartTime = strtotime(date('Y-m'));
        $monthEndTime = time();
        foreach ($product as $key => $val) {
            $product[$key]["day_date"] = date('m-d', $dayStartTime);
            $product[$key]["day_total"] = 0;
            $product[$key]["month_total"] = 0;
            $product[$key]["day_hb_type"] = 2;
            $product[$key]["day_hb"] = 0;
            $product[$key]["month_hb_type"] = 2;
            $product[$key]["month_hb"] = 0;
            if (!empty($val["table_name"])) {
                $dayData = Lib::getTeamActiveData($ids, $val["id"], 2, $dayStartTime, $dayEndTime);
                $prevDayData = Lib::getTeamActiveData($ids, $val["id"], 2, strtotime('-1 month', $dayStartTime), strtotime('-1 month', $dayEndTime));
                $monthData = Lib::getTeamActiveData($ids, $val["id"], 2, $monthStartTime, $monthEndTime);
                $prevMonthData = Lib::getTeamActiveData($ids, $val["id"], 2, strtotime('-1 month', $monthStartTime), strtotime('-1 month', $monthEndTime));
                $product[$key]["day_total"] = $dayData["total"];
                $product[$key]["month_total"] = $monthData["total"];
                $hbDayData = calculateHb($dayData['total'], $prevDayData["total"]);
                $product[$key]["day_hb_type"] = $hbDayData["hb_type"];
                $product[$key]["day_hb"] = floor($hbDayData["hb_num"]);
                $hbMonthData = calculateHb($monthData['total'], $prevMonthData["total"]);
                $product[$key]["month_hb_type"] = $hbMonthData["hb_type"];
                $product[$key]["month_hb"] = floor($hbMonthData["hb_num"]);
            }
        }
        $this->success('获取成功', $product);
    }

    /**
     * 数据 按【产品、团队】统计 - 交易
     */
    public function getProductTeamTranData()
    {
        $productId = $this->request->post('product_id');
        $teamId = $this->request->post('team_id');
        $type = $this->request->post('type');
        $startTime = strtotime('-5 month', strtotime(date('Y-m-01')));
        $data = [
            'time' => date('Y-m-d', strtotime('-1 day')) . ' 23:59:59',
            'all_total' => '0.00',
            'list' => []
        ];
        if (empty($productId) || empty($type)) {
            $this->error('缺少参数');
        }
        $tableName = Product::where('id', $productId)->value('table_name');
        if (!empty($tableName)) {
            switch ($type) {
                case 'ALL':
                    $teamIds = Lib::getTeamAllUser($this->auth->id);
                    break;
                case 'MY':
                    $teamIds = [$this->auth->id];
                    break;
                case 'TEAM':
                    $teamIds = Lib::getTeamAllUser($teamId);
                    break;
            }
            $totalData = Lib::getProductDateGroup($teamIds, $productId, $tableName, $startTime);
            if (!empty($totalData)) {
                foreach ($totalData as $key => $val) {
                    $data["all_total"] = bcadd($data["all_total"], $val["total"], 2);
                    $totalData[$key]['child_list'] = Lib::getProductDateGroup($teamIds, $productId, $tableName, $startTime, 2, $val['date']);
                }
            }
            $data["list"] = $totalData;
        }
        $this->success('获取成功', $data);
    }

    /**
     * 数据 按【产品、团队、月份】统计 - 交易
     */
    public static function getProductMonthTeamTranData5($productIds, $teamIds, $date)
    {
        $startTime = strtotime('-5 month', strtotime(date('Y-m-01')));

        $allData = [];
        $days = [];

        foreach ($productIds as $val) {
            if (!empty($val["table_name"])) {
                $totalData = Lib::getProductDateGroup($teamIds, $val["id"], $val["table_name"], $startTime, 2, $date);
                if (!empty($totalData)) {
                    foreach ($totalData as $vals) {
                        $allData[] = $vals;
                        $days[] = strtotime($vals["date"]);
                    }
                }
            }
        }

        $days = array_unique($days);
        rsort($days, 1);

        $list = [];
        foreach ($days as $key => $val) {
            $list[$key] = [
                "date" => date('Y-m-d', $val),
                "total" => 0
            ];
            foreach ($allData as $vals) {
                if ($val == strtotime($vals["date"])) {
                    $list[$key]["total"] = bcadd($list[$key]["total"], $vals["total"], 2);
                }
            }
        }
        return $list;
    }

    // 数据统计
    public function getProductTeamTranData5()
    {
        $productId = $this->request->post('product_id', '');
        $teamId = $this->request->post('team_id');
        $type = $this->request->post('type');
        $tranType = $this->request->post('tran_type', 0);

        $productIds = [];
        $startTime = strtotime('-5 month', strtotime(date('Y-m-01')));
        $data = [
            'time' => date('Y-m-d', strtotime('-1 day')) . ' 23:59:59',
            'all_total' => '0.00',
            'list' => []
        ];
        if (empty($type)) {
            $this->error('缺少参数');
        }

        switch ($type) {
            case 'ALL':
                $teamIds = Lib::getTeamAllUser5($this->auth->id);
                break;
            case 'MY':
                $teamIds = [$this->auth->id];
                break;
            case 'TEAM':
                $teamIds = Lib::getTeamAllUser5($teamId);
                break;
        }

        if ($productId <= 0) {
            $product = Db::name('product')->field("id")->where('status', 1)->select();
            foreach ($product as $key => $value) {
                $productIds[] = $value['id'];
            }
        } else {
            $productIds = [$productId];
        }

        // 统计总交易额
        $totalQuery = Db::name('transaction_statistics')
            ->whereIn("main_id", $teamIds)
            ->whereIn("product_id", $productIds);
        if ($tranType > 0) {
            $totalQuery->where(['tran_type' => $tranType]);
        }
        $totalData =  $totalQuery->field("sum(total_amount) as total_amount")
            ->find();
        $data["all_total"] = !empty($totalData["total_amount"]) ? $totalData["total_amount"] : '0.00';

        // 分组查询统计
        $query1 = Db::name('transaction_statistics')
            ->whereIn("main_id", $teamIds)
            ->whereIn("product_id", $productIds);
        if ($tranType > 0) {
            $query1->where(['tran_type' => $tranType]);
        }
        $twoData = $query1->field("sum(total_amount) as total, month as date")
            ->group("month")
            ->order("month desc")
            ->select();

        foreach ($twoData as $key => $value) {
            $query2 = Db::name('transaction_statistics')
                ->whereIn("main_id", $teamIds)
                ->whereIn("product_id", $productIds)
                ->where("month", $value["date"]);
            if ($tranType > 0) {
                $query2->where(['tran_type' => $tranType]);
            }
            $twoData[$key]["child_list"] = $query2->field("sum(total_amount) as total, day as date")
                ->group("day")
                ->order("day desc")
                ->select();
        }

        $data["list"] = $twoData;

        $this->success('获取成功', $data);
    }

    /**
     * 数据 获取交易详情 统计
     */
    public function getTranDetailTotal()
    {
        $productId = $this->request->post('product_id');
        $date = $this->request->post('date');
        $type = $this->request->post('type', 1);
        $search = $this->request->post('search');
        $data = ['total' => 0, 'sum' => '0.00'];
        if (empty($productId)) {
            $this->error('缺少参数');
        }
        switch ($type) {
            case 1:
                $startTime = strtotime($date);
                $endTime = strtotime('+1 day', $startTime);
                break;
            case 2:
                $startTime = strtotime('-7 day', strtotime($date));
                $endTime = strtotime('+1 day', strtotime($date));
                break;
            case 3:
                $startTime = strtotime('-1 month', strtotime($date));
                $endTime = strtotime('+1 day', strtotime($date));
                break;
        }
        $tableName = Product::where('id', $productId)->value('table_name');
        if (!empty($tableName)) {
            $data = Lib::getTeamTranData([$this->auth->id], $tableName, $productId, 2, $startTime, $endTime, $search);
        }
        $this->success('获取成功', $data);
    }

    /**
     * 数据 获取交易详情 统计 5.0
     */
    public function getTranDetailTotal5()
    {
        $productId = $this->request->post('product_id', '');
        $date = $this->request->post('date');
        $type = $this->request->post('type', 1);
        $search = $this->request->post('search');
        $data = ['total' => 0, 'sum' => '0.00'];
        $teamId = $this->request->post('team_id');
        $tranType = $this->request->post('tran_type', 0);

        if ($productId <= 0) {
            $productIds = Lib::getMyProduct5($this->auth->id, 2);
        } else {
            $productIds = Db::name("product")->where('id', $productId)->field("id,name,table_name")->select();
        }

        if ($teamId == "all") {
            $userIds = array_merge([$this->auth->id], Tools::getUserChild($this->auth->id, 4));
        } elseif ($teamId == "0") {
            $userIds = [$this->auth->id];
        } else {
            $userIds = array_merge([$teamId], Tools::getUserChild($teamId, 4));
        }

        foreach ($productIds as $val) {
            if (!empty($val["table_name"])) {
                switch ($type) {
                    case 1:
                        $startTime = strtotime($date);
                        $endTime = strtotime('+1 day', $startTime);
                        break;
                    case 2:
                        $startTime = strtotime('-7 day', strtotime($date));
                        $endTime = strtotime('+1 day', strtotime($date));
                        break;
                    case 3:
                        $startTime = strtotime('-1 month', strtotime($date));
                        $endTime = strtotime('+1 day', strtotime($date));
                        break;
                }
                $datas = Lib::getTeamTranData([$this->auth->id], $val["table_name"], $val["id"], 2, $userIds, $tranType, $startTime, $endTime, $search);
                if (!empty($datas)) {
                    $data["total"] += $datas["total"];
                    $data["sum"] = bcadd($data["sum"], $datas["sum"], 2);
                }
            }
        }

        $this->success('获取成功', $data);
    }

    /**
     * 数据 获取交易详情
     */
    public function getTranDetail()
    {
        $productId = $this->request->post('product_id');
        $date = $this->request->post('date');
        $type = $this->request->post('type', 1);
        $search = $this->request->post('search');
        $pageSize = $this->request->post('page_size', 10);
        $data = [];
        if (empty($productId) || empty($date)) {
            $this->error('缺少参数');
        }
        switch ($type) {
            case 1:
                $startTime = strtotime($date);
                $endTime = strtotime('+1 day', $startTime);
                break;
            case 2:
                $startTime = strtotime('-7 day', strtotime($date));
                $endTime = strtotime('+1 day', strtotime($date));
                break;
            case 3:
                $startTime = strtotime('-1 month', strtotime($date));
                $endTime = strtotime('+1 day', strtotime($date));
                break;
        }
        $tableName = Product::where('id', $productId)->value('table_name');
        if (!empty($tableName)) {
            $data = Lib::getTranDetailList([$this->auth->id], $productId, $tableName, $startTime, $endTime, $search, $pageSize);
            $data = $data->items();
        }
        $this->success('获取成功', $data);
    }

    /**
     * 数据 获取交易详情
     */
    public function getTranDetail5()
    {
        $productId = $this->request->post('product_id');
        $date = $this->request->post('date');
        $type = $this->request->post('type', 1);
        $search = $this->request->post('search');
        $pageSize = $this->request->post('page_size', 10);
        $teamId = $this->request->post('team_id');
        $tranType = $this->request->post('tran_type', 0);
        $data = [];
        if (empty($date)) {
            $this->error('缺少参数');
        }

        if ($productId <= 0) {
            $productIds = Lib::getMyProduct5($this->auth->id, 2);
        } else {
            $productIds = Db::name("product")->where('id', $productId)->field("id,name,table_name")->select();
        }

        if ($teamId == "all") {
            $userIds = array_merge([$this->auth->id], Tools::getUserChild($this->auth->id, 4));
        } elseif ($teamId == "0") {
            $userIds = [$this->auth->id];
        } else {
            $userIds = array_merge([$teamId], Tools::getUserChild($teamId, 4));
        }

        foreach ($productIds as $val) {
            if (!empty($val["table_name"])) {
                switch ($type) {
                    case 1:
                        $startTime = strtotime($date);
                        $endTime = strtotime('+1 day', $startTime);
                        break;
                    case 2:
                        $startTime = strtotime('-7 day', strtotime($date));
                        $endTime = strtotime('+1 day', strtotime($date));
                        break;
                    case 3:
                        $startTime = strtotime('-1 month', strtotime($date));
                        $endTime = strtotime('+1 day', strtotime($date));
                        break;
                }
                $datas = Lib::getTranDetailList5([$this->auth->id], $val["id"], $val["table_name"], $userIds, $startTime, $endTime, $search, $tranType, $pageSize);
                $data = array_merge($data, $datas);
            }
        }
        $data = arraySort($data, "trading_time", 'desc');
        $this->success('获取成功', $data);
    }

    /**
     * 数据 按【产品、团队】统计 - 激活
     */
    public function getProductTeamActiveData()
    {
        $productId = $this->request->post('product_id');
        $teamId = $this->request->post('team_id');
        $type = $this->request->post('type');
        $startTime = strtotime('-5 month', strtotime(date('Y-m-01')));
        $data = [
            'time' => date('Y-m-d', strtotime('-1 day')) . ' 23:59:59',
            'all_total' => 0,
            'list' => []
        ];
        if (empty($productId) || empty($type)) {
            $this->error('缺少参数');
        }
        $tableName = Product::where('id', $productId)->value('table_name');
        if (!empty($tableName)) {
            switch ($type) {
                case 'ALL':
                    $teamIds = Lib::getTeamAllUser($this->auth->id);
                    break;
                case 'MY':
                    $teamIds = [$this->auth->id];
                    break;
                case 'TEAM':
                    $teamIds = Lib::getTeamAllUser($teamId);
                    break;
            }
            $totalData = Lib::getProductDateActiveGroup($teamIds, $productId, $startTime);
            if (!empty($totalData)) {
                foreach ($totalData as $key => $val) {
                    $data["all_total"] += $val["total"];
                    $totalData[$key]['child_list'] = Lib::getProductDateActiveGroup($teamIds, $productId, $startTime, 2, $val['date']);
                }
            }
            $data["list"] = $totalData;
        }
        $this->success('获取成功', $data);
    }

    /**
     * 数据 按【产品、团队】统计 - 激活 5.0
     */
    public function getProductTeamActiveData5()
    {
        $productId = $this->request->post('product_id', '');
        $teamId = $this->request->post('team_id');
        $type = $this->request->post('type');
        $startTime = strtotime('-5 month', strtotime(date('Y-m-01')));
        $data = [
            'time' => date('Y-m-d', strtotime('-1 day')) . ' 23:59:59',
            'all_total' => 0,
            'list' => []
        ];
        if (empty($type)) {
            $this->error('缺少参数');
        }
        if ($productId <= 0) {
            $productIds = Lib::getMyProduct5($this->auth->id, 2);
        } else {
            $productIds = Db::name("product")->where('id', $productId)->field("id,name,table_name")->select();
        }

        switch ($type) {
            case 'ALL':
                $teamIds = Lib::getTeamAllUser($this->auth->id);
                break;
            case 'MY':
                $teamIds = [$this->auth->id];
                break;
            case 'TEAM':
                $teamIds = Lib::getTeamAllUser($teamId);
                break;
        }

        $allData = [];
        $days = [];

        foreach ($productIds as $val) {
            if (!empty($val["table_name"])) {
                $totalData = Lib::getProductDateActiveGroup($teamIds, $val["id"], $startTime);
                if (!empty($totalData)) {
                    foreach ($totalData as $vals) {
                        $allData[] = $vals;
                        $data["all_total"] += $vals["total"];
                        $days[] = strtotime($vals["date"]);
                    }
                }
            }
        }

        $days = array_unique($days);
        rsort($days, 1);

        $lists = [];
        foreach ($days as $key => $val) {
            $lists[$key] = [
                "date" => date('Y-m', $val),
                "total" => 0
            ];
            foreach ($allData as $vals) {
                if ($val == strtotime($vals["date"])) {
                    $lists[$key]["total"] += $vals["total"];
                }
            }
        }

        foreach ($lists as $key => $val) {
            $lists[$key]["child_list"] = self::getProductMonthTeamActiveData5($productIds, $teamIds, $val["date"]);
        }

        $data["list"] = $lists;

        $this->success('获取成功', $data);
    }

    /**
     * 数据 按【产品、团队、月份】统计 - 交易
     */
    public static function getProductMonthTeamActiveData5($productIds, $teamIds, $date)
    {
        $startTime = strtotime('-5 month', strtotime(date('Y-m-01')));

        $allData = [];
        $days = [];

        foreach ($productIds as $val) {
            if (!empty($val["table_name"])) {
                $totalData = Lib::getProductDateActiveGroup($teamIds, $val["id"], $startTime, 2, $date);
                if (!empty($totalData)) {
                    foreach ($totalData as $vals) {
                        $allData[] = $vals;
                        $days[] = strtotime($vals["date"]);
                    }
                }
            }
        }

        $days = array_unique($days);
        rsort($days, 1);

        $list = [];
        foreach ($days as $key => $val) {
            $list[$key] = [
                "date" => date('Y-m-d', $val),
                "total" => 0
            ];
            foreach ($allData as $vals) {
                if ($val == strtotime($vals["date"])) {
                    $list[$key]["total"] += $vals["total"];
                }
            }
        }
        return $list;
    }

    /**
     * 数据 获取激活详情 统计
     */
    public function getActiveDetailTotal()
    {
        $productId = $this->request->post('product_id');
        $date = $this->request->post('date');
        $type = $this->request->post('type', 1);
        $search = $this->request->post('search');
        $data = ['total' => 0];
        if (empty($productId)) {
            $this->error('缺少参数');
        }
        switch ($type) {
            case 1:
                $startTime = strtotime($date);
                $endTime = strtotime('+1 day', $startTime);
                break;
            case 2:
                $startTime = strtotime('-7 day', strtotime($date));
                $endTime = strtotime('+1 day', strtotime($date));
                break;
            case 3:
                $startTime = strtotime('-1 month', strtotime($date));
                $endTime = strtotime('+1 day', strtotime($date));
                break;
        }
        $data = Lib::getTeamActiveData([$this->auth->id], $productId, 2, $startTime, $endTime, $search);
        $this->success('获取成功', $data);
    }

    /**
     * 数据 获取激活详情 统计 5.0
     */
    public function getActiveDetailTotal5()
    {
        $productId = $this->request->post('product_id');
        $date = $this->request->post('date');
        $type = $this->request->post('type', 1);
        $search = $this->request->post('search');
        $productIds = [];
        $productIdArr = [];
        $data = ['total' => 0];
        if ($productId <= 0) {
            $productIds = Lib::getMyProduct5($this->auth->id, 2);
        } else {
            $productIds = Db::name("product")->where('id', $productId)->field("id,name,table_name")->select();
        }

        foreach ($productIds as $val) {
            $productIdArr[] = $val["id"];
        }

        switch ($type) {
            case 1:
                $startTime = strtotime($date);
                $endTime = strtotime('+1 day', $startTime);
                break;
            case 2:
                $startTime = strtotime('-7 day', strtotime($date));
                $endTime = strtotime('+1 day', strtotime($date));
                break;
            case 3:
                $startTime = strtotime('-1 month', strtotime($date));
                $endTime = strtotime('+1 day', strtotime($date));
                break;
        }
        $data = Lib::getTeamActiveData5([$this->auth->id], $productIdArr, 2, $startTime, $endTime, $search);
        $this->success('获取成功', $data);
    }

    /**
     * 数据 获取激活详情
     */
    public function getActiveDetail()
    {
        $productId = $this->request->post('product_id');
        $date = $this->request->post('date');
        $type = $this->request->post('type', 1);
        $search = $this->request->post('search');
        $pageSize = $this->request->post('page_size', 10);
        $data = [];
        if (empty($productId) || empty($date)) {
            $this->error('缺少参数');
        }
        switch ($type) {
            case 1:
                $startTime = strtotime($date);
                $endTime = strtotime('+1 day', $startTime);
                break;
            case 2:
                $startTime = strtotime('-7 day', strtotime($date));
                $endTime = strtotime('+1 day', strtotime($date));
                break;
            case 3:
                $startTime = strtotime('-1 month', strtotime($date));
                $endTime = strtotime('+1 day', strtotime($date));
                break;
        }
        $tableName = Product::where('id', $productId)->value('table_name');
        if (!empty($tableName)) {
            $data = Lib::getActiveDetailList([$this->auth->id], $productId, $tableName, $startTime, $endTime, $search, $pageSize);
            $data = $data->items();
        }
        $this->success('获取成功', $data);
    }

    /**
     * 数据 获取激活详情 5.0
     */
    public function getActiveDetail5()
    {
        $productId = $this->request->post('product_id');
        $date = $this->request->post('date');
        $type = $this->request->post('type', 1);
        $search = $this->request->post('search');
        $pageSize = $this->request->post('page_size', 10);
        $productIds = [];
        $data = [];
        if (empty($date)) {
            $this->error('缺少参数');
        }
        if ($productId <= 0) {
            $productIds = Lib::getMyProduct5($this->auth->id, 2);
        } else {
            $productIds = Db::name("product")->where('id', $productId)->field("id,name,table_name")->select();
        }

        foreach ($productIds as $val) {
            if (!empty($val["table_name"])) {
                switch ($type) {
                    case 1:
                        $startTime = strtotime($date);
                        $endTime = strtotime('+1 day', $startTime);
                        break;
                    case 2:
                        $startTime = strtotime('-7 day', strtotime($date));
                        $endTime = strtotime('+1 day', strtotime($date));
                        break;
                    case 3:
                        $startTime = strtotime('-1 month', strtotime($date));
                        $endTime = strtotime('+1 day', strtotime($date));
                        break;
                }
                $datas = Lib::getActiveDetailList5([$this->auth->id], $val["id"], $val["table_name"], $startTime, $endTime, $search, $pageSize);
                $data = array_merge($data, $datas);
            }
        }
        $this->success('获取成功', $data);
    }

    /**
     * 根据产品获取代理人数
     */
    public function getProductTeam()
    {
        $type = $this->request->post('type', 1);
        $product = Lib::getMyProduct5($this->auth->id, 2);
        $myTeam = Lib::getMyTeamId($this->auth->id);
        $teamId = $myTeam;
        $startTime = strtotime(date('Y-m'));
        if ($type == 2) {
            $teamId = Lib::getTeamAllUser($this->auth->id, 2);
        }
        foreach ($product as $key => $val) {
            $product[$key]["user_month_nums"] = Lib::getProductTeam($teamId, $val["id"], $startTime, time());
            $product[$key]["user_all_nums"] = Lib::getProductTeam($teamId, $val["id"]);
        }
        $this->success('获取成功', $product);
    }

    /**
     * 根据产品获取代理人数 - 详情 - 统计
     */
    public function getProductTeamDetailCount()
    {
        $productId = $this->request->post('product_id');
        if (isset($productId) && !empty($productId) && $productId > 0) {
            $myTeam = Lib::getMyTeamId($this->auth->id);
            $data = [
                "total" => 0,
                "month" => 0,
                "last_month" => 0
            ];
            $startTime = strtotime(date('Y-m'));
            $endTime = time();
            $data["total"] = Lib::getProductTeam($myTeam, $productId);
            $data["month"] = Lib::getProductTeam($myTeam, $productId, $startTime, $endTime);
            $endTime = $startTime;
            $startTime = strtotime('-1 month', $startTime);
            $data["last_month"] = Lib::getProductTeam($myTeam, $productId, $startTime, $endTime);
            $this->success('获取成功', $data);
        } else {
            $this->error('参数错误！');
        }
    }

    /**
     * 根据产品获取代理人数 - 详情
     */
    public function getProductTeamDetail()
    {
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('page_size', 15);
        $productId = $this->request->post('product_id');
        if (isset($productId) && !empty($productId) && $productId > 0) {
            $myTeam = Lib::getMyTeamId($this->auth->id);
            $data = Lib::getProductTeamDetail($myTeam, $productId, $pageSize);
            $data = $data->items();
            foreach ($data as $key => $val) {
                $data[$key]["team_nums"] = Lib::getProductTeam(Lib::getTeamAllUser($val["id"], 2), $productId);
            }
            $this->success('获取成功', $data);
        } else {
            $this->error('参数错误！');
        }
    }

    /**
     * 获取代理人数 - 详情 - 统计
     */
    public function getTeamDetailCount()
    {
        $type = $this->request->post('type');
        if (isset($type) && !empty($type) && $type > 0) {
            $data = [
                "total" => 0,
                "month" => 0,
                "last_month" => 0
            ];
            if ($type == 1) {
                $teamIds = [$this->auth->id];
            } else {
                $teamIds = Lib::getTeamAllUser($this->auth->id);
            }
            $startTime = strtotime(date('Y-m'));
            $endTime = time();
            $data["total"] = Db::name("user")
                ->where(["ptype" => 2, "status" => "normal", "is_virtual" => 1])
                ->whereIn("pid", $teamIds)
                ->count();
            $data["month"] = Db::name("user")
                ->where(["ptype" => 2, "status" => "normal", "is_virtual" => 1])
                ->whereIn("pid", $teamIds)
                ->where('createtime', 'between', [$startTime, $endTime])
                ->count();
            $endTime = $startTime;
            $startTime = strtotime('-1 month', $startTime);
            $data["last_month"] = Db::name("user")
                ->where(["ptype" => 2, "status" => "normal", "is_virtual" => 1])
                ->whereIn("pid", $teamIds)
                ->where('createtime', 'between', [$startTime, $endTime])
                ->count();
            $this->success('获取成功', $data);
        } else {
            $this->error('参数错误！');
        }
    }

    /**
     * 获取代理人数 - 详情
     */
    public function getTeamDetail()
    {
        // $page = $this->request->post('page', 1);
        // $pageSize = $this->request->post('page_size', 15);
        // $type = $this->request->post('type');
        // if (isset($type) && !empty($type) && $type > 0) {
        //     $fields = "id,username,nickname,mobile,avatar,FROM_UNIXTIME(createtime, '%Y-%m-%d %H:%m:%s') createtime";
        //     $data = Db::name("user")
        //         ->where(["ptype" => 2, "pid" => $this->auth->id, "status" => "normal", "is_virtual" => 1])
        //         ->field($fields)->order("createtime desc")->paginate($pageSize);
        //     $data = $data->items();
        //     foreach ($data as $key => $val) {
        //         $data[$key]["team_nums"] = count(Lib::getTeamAllUser($val["id"], 2));
        //     }
        //     $this->success('获取成功', $data);
        // } else {
        //     $this->error('参数错误！');
        // }
        $uid = $this->auth->id;
        $page = $this->request->post("page");
        $req = \app\api\controller\teams\Teams::instance()->lists($uid, $page);
        if ($req === false) {
            $this->error(Config("msg")["0003"]);
        }
        $this->success("账单-类型-详情", ["counts" => count($req), "data" => $req]);
    }

    /**
     * 根据产品统计当日收益
     */
    public function getProductDayIncome()
    {
        $uid = $this->auth->id;
        $date = $this->request->post('date');
        $typs = $this->request->post("typs");
        $dayTyps = $this->request->post("dayTyps");
        $counts = 0;
        $product = [];
        $selectTyps = 1;
        $ex = explode("_", $date);
        $dayTyps && $selectTyps = $dayTyps;
        if ($selectTyps == 1) {
            if (count($ex) == 1) {
                $product = \app\api\controller\balance\Details::instance()->lists($uid, $date, $typs);
                $counts = count($product);
            }
        }
        if ($selectTyps == 2) {
            if (count($ex) == 2) {
                $product = \app\api\controller\balance\Details::instance()->rangsLists($uid, $date, $typs);
                $counts = count($product);
            }
        }
        $this->success('账户明细', ["counts" => $counts, "product" => $product]);
    }

    /**
     * 账单-类型-详情
     */
    public function accout_typs_details()
    {
        $uid = $this->auth->id;
        $date = $this->request->post('date');
        $typs = $this->request->post("typs");
        $isChg = $this->request->post("isChg");
        $proid = $this->request->post("proid");
        $start = $this->request->post("start_time");
        $page = $this->request->post("page");

        $dayTyps = $this->request->post("dayTyps");
        $data = [];
        $selectTyps = 1;
        $ex = explode("_", $date);
        $dayTyps && $selectTyps = $dayTyps;

        if ($selectTyps == 1) {
            $data = \app\api\controller\balance\Details::instance()->account_details($uid, $typs, $proid, $isChg, $date, $start, $page);
            if ($data === false) {
                $this->error("查找信息异常！！！");
            }
        }
        if ($selectTyps == 2) {
            if (count($ex) == 2) {
                $data = \app\api\controller\balance\Details::instance()->range_account_details($uid, $typs, $proid, $isChg, $date, $page);
                if ($data === false) {
                    $this->error("查找信息异常！！！");
                }
            }
        }

        $this->success("账单-类型-详情", ["counts" => count($data), "data" => $data]);
    }

    /**
     * 分红明细
     */
    protected function bonus($id, $times)
    {
        $data = [];
        $date = date("Y-m", strtotime("-1 month", strtotime($times)));
        $res = Db::name("balance_type")->where("name = '分红收益'")->value("id");
        if ($res) {
            $where = "agid = {$id} and ( create_time >= " . strtotime($times) . " and  create_time < " . strtotime("+1 day ", strtotime($times)) . " )";
            $con = Db::name("bonus_details")
                ->where($where)
                ->count();
            if ($con) {
                $earn_total = Db::name("bonus_details")->where($where)->sum("earns");

                $lists = Db::name("bonus_details")->field("id,lev_code name,earns total")->where($where)->select();

                if (count($lists) > 0) {
                    foreach ($lists as $k => $v) {
                        $lists[$k]['name'] = $v["name"] . "阶段奖励";
                        $lists[$k]['moneyTypeData'] = [];
                    }
                    $data[] = [
                        "id" => "P_" . $id,
                        "name" => "分红",
                        "table_name" => "",
                        "total" => [
                            "total" => $earn_total,
                            "counts" => $con,
                        ],
                        "balanceTypeNums" => 1,
                        "balanceTypeData" => $lists
                        // [
                        //     [
                        //         "id" => $res,
                        //         "name" => "分红收益",
                        //         "total" => $earn_total,
                        //         "counts" =>  $con,
                        //         "moneyTypeNums" => 1,
                        //         "moneyTypeData" =>  []
                        //     ]
                        // ]
                    ];
                }
            }
        }
        return $data;
    }

    public function get_bonus_datas($id)
    {
    }

    /**
     * 数据 - 详情 - 获取我的产品
     */
    public function getMyProduct()
    {
        $datas = [
            ["id" => '', "label" => "全部产品"]
        ];
        // $data = Lib::getMyProductData5($this->auth->id, 2);
        $data = Db::name("product")->field("id,name label")->where(["status" => 1, "sell_state" => 1])->order("create_time desc")->select();
        foreach ($data as $val) {
            $datas[] = $val;
        }
        $this->success('我的产品', $datas);
    }

    // 统计交易数据
    public function transactionStatistics()
    {
        $db_type = $this->request->get('db_type', 'jl');
        $date = date('Y-m-d');
        $type = 'D';
        if ($type == 'D') {
            $startTime = strtotime('-1 day', strtotime($date));
            $endTime = strtotime($date);
        } else {
            $startTime = strtotime(date('Y-m-01', strtotime($date)));
            $endTime = strtotime(date('Y-m-01', strtotime('+1 month', strtotime($date))));
        }

        $tables = "transaction_data_" . $db_type;
        $data = Db::name($tables)->alias("a")
            ->join("equip b", "a.sn = b.sn", "LEFT")
            ->field('a.sn,count(*) nums,SUM(a.transaction_amount) amount,FROM_UNIXTIME(a.trading_time, "%Y-%m-%d") trading_date,b.main_id,b.product_id,a.tran_type')
            ->where('a.trading_time', 'between', [$startTime, $endTime])
            ->group("a.sn,trading_date,a.tran_type")
            ->order("trading_date ASC")
            ->select();

        if (count($data) > 0) {
            foreach ($data as $key => $val) {
                self::saveTransactionStatistics($val);
            }
        }
    }

    // 存储统计数据
    public static function saveTransactionStatistics($data)
    {
        $sqlData = [];
        if ($data["product_id"] > 0) {
            $where = [
                "main_id" => $data["main_id"],
                "product_id" => $data["product_id"],
                "sn" => $data["sn"],
                "day" => $data["trading_date"],
                "tran_type" => $data["tran_type"],
            ];
            $count = Db::name("transaction_statistics")->where($where)->count();
            if ($count <= 0) {
                $sqlData = $where;
                $sqlData["month"] = date('Y-m', strtotime($where["day"]));
                $sqlData["nums"] = $data["nums"];
                $sqlData["total_amount"] = $data["amount"];
                Db::name("transaction_statistics")->insert($sqlData);
            }
        }
    }

    //--------------------------------------Pro1.0 数据统计--------------------------------------------------

    public function getFlowData()
    {
        $productId = $this->request->post('product_id', 0);
        $type = $this->request->post('type', "all");
        $howMany = $this->request->post('how_many', 0);

        if ($productId == 0) {
            $productIds = Libs::getAllProductIds();
        } else {
            $productIds = [$productId];
        }

        $startTime = strtotime(date("Y-m", strtotime("-5 month")));
        if ($type == "all") {
            $userIds = array_merge([$this->auth->id], Tools::getUserChild($this->auth->id, 4));
        } elseif ($type == "0") {
            $userIds = [$this->auth->id];
            //            $ids = Tools::getUserChild($this->auth->id,2);
            //            foreach ($ids as $key => $val){
            //                $userIds[] = $val['id'];
            //            }
        } else {
            $userIds = array_merge([$type], Tools::getUserChild($type, 4));
        }

        $list = Libs::getFlowData($productIds, $startTime, $userIds, $howMany);
        foreach ($list as $key => &$val) {
            $val['child_list'] = Libs::getFlowData($productIds, $startTime, $userIds, $howMany, $val['date']);
        }
        unset($val);

        $data['all_total'] = Libs::getFlowCount($productIds, $startTime, $userIds, $howMany);
        $data['list'] = $list;
        $data['time'] = date('Y-m-d', strtotime('-1 day')) . ' 23:59:59';

        $this->success("数据统计", $data);
    }

    public function getFLowTimes()
    {
        $startTime = strtotime(date("Y-m", strtotime("-5 month")));
        $userIds = array_merge([$this->auth->id], Tools::getUserChild($this->auth->id, 4));

        $data = [
            [
                "times" => 0,
                "name" => "全部次数"
            ]
        ];
        $list = Libs::getFlowTimes($startTime, $userIds);
        foreach ($list as $key => $val) {
            $data[] = [
                "times" => $val,
                "name" => "第" . $val . "次"
            ];
        }

        $this->success("流量卡次数", $data);
    }

    public function getFlowDetails()
    {
        $productId = $this->request->post('product_id', 0);
        $type = $this->request->post('type', "all");
        $howMany = $this->request->post('how_many', 0);
        $day = $this->request->post('day');
        $search = $this->request->post('search', "");

        if ($productId == 0) {
            $productIds = Libs::getAllProductIds();
        } else {
            $productIds = [$productId];
        }

        $startTime = strtotime(date("Y-m", strtotime("-5 month")));
        if ($type == "all") {
            $userIds = array_merge([$this->auth->id], Tools::getUserChild($this->auth->id, 4));
        } elseif ($type == "0") {
            $userIds = [$this->auth->id];
            //            $ids = Tools::getUserChild($this->auth->id,2);
            //            foreach ($ids as $key => $val){
            //                $userIds[] = $val['id'];
            //            }
        } else {
            $userIds = array_merge([$type], Tools::getUserChild($type, 4));
        }

        $list = Libs::getFlowDetails($productIds, $startTime, $userIds, $howMany, $day, $search);
        foreach ($list as $key => &$val) {
            $val['end_time'] = date("Y-m-d H:i:s", $val['end_time']);
            $val['active_time'] = date("Y-m-d H:i:s", $val['active_time']);
            $val['binding_time'] = date("Y-m-d H:i:s", $val['binding_time']);
            $val['trading_time'] = date("Y-m-d H:i:s", $val['trading_time']);
            $val['create_time'] = date("Y-m-d H:i:s", $val['create_time']);
        }
        unset($val);

        $this->success("流量卡详情", $list);
    }

    public function getStandardData()
    {
        $productId = $this->request->post('product_id', 0);
        $type = $this->request->post('type', "all");
        $status = $this->request->post('status', 0);

        if ($productId == 0) {
            $productIds = Libs::getAllProductIds();
        } else {
            $productIds = [$productId];
        }

        $startTime = strtotime(date("Y-m", strtotime("-5 month")));
        if ($type == "all") {
            $userIds = array_merge([$this->auth->id], Tools::getUserChild($this->auth->id, 4));
        } elseif ($type == "0") {
            $userIds = [$this->auth->id];
            //            $ids = Tools::getUserChild($this->auth->id,2);
            //            foreach ($ids as $key => $val){
            //                $userIds[] = $val['id'];
            //            }
        } else {
            $userIds = array_merge([$type], Tools::getUserChild($type, 4));
        }

        $list = Libs::getStandardData($productIds, $startTime, $userIds, $status);
        foreach ($list as $key => &$val) {
            $val['child_list'] = Libs::getStandardData($productIds, $startTime, $userIds, $status, $val['date']);
        }
        unset($val);

        $data['all_total'] = Libs::getStandardCount($productIds, $startTime, $userIds, $status);
        $data['list'] = $list;
        $data['time'] = date('Y-m-d', strtotime('-1 day')) . ' 23:59:59';

        $this->success("数据统计", $data);
    }

    public function getStandardDetails()
    {
        $productId = $this->request->post('product_id', 0);
        $type = $this->request->post('type', "all");
        $status = $this->request->post('status', 0);
        $day = $this->request->post('day');
        $search = $this->request->post('search', "");

        if ($productId == 0) {
            $productIds = Libs::getAllProductIds();
        } else {
            $productIds = [$productId];
        }

        $startTime = strtotime(date("Y-m", strtotime("-5 month")));
        if ($type == "all") {
            $userIds = array_merge([$this->auth->id], Tools::getUserChild($this->auth->id, 4));
        } elseif ($type == "0") {
            $userIds = [$this->auth->id];
            //            $ids = Tools::getUserChild($this->auth->id,2);
            //            foreach ($ids as $key => $val){
            //                $userIds[] = $val['id'];
            //            }
        } else {
            $userIds = array_merge([$type], Tools::getUserChild($type, 4));
        }

        $list = Libs::getStandardDetails($productIds, $startTime, $userIds, $status, $day, $search);
        foreach ($list as $key => &$val) {
            $val['end_time'] = date("Y-m-d H:i:s", $val['end_time']);
            $val['active_time'] = date("Y-m-d H:i:s", $val['active_time']);
            $val['binding_time'] = date("Y-m-d H:i:s", $val['binding_time']);
            $val['trading_time'] = date("Y-m-d H:i:s", $val['trading_time']);
            $val['create_time'] = date("Y-m-d H:i:s", $val['create_time']);
        }

        $this->success("达标详情", $list);
    }
    /**
     * 获取最大最小日期
     */
    public function getMaxMinData()
    {
        $maxDate = date('Y-m-d', strtotime('-1 day'));
        $minDate = date('Y-m-01', strtotime('-5 month'));
        $this->success("达标详情", ["minDate" => $minDate, "maxDate" => $maxDate]);
    }
}
